package drongo.desktop.tools
{
	import drongo.desktop.tools.events.TraceableEvent;
	
	import flash.desktop.NativeProcess;
	import flash.desktop.NativeProcessStartupInfo;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.NativeProcessExitEvent;
	import flash.events.ProgressEvent;
	import flash.filesystem.File;
	
	/**
	 * AIR调用外部程序工具类
	 * @author Greg
	 */	
	public class AIRExternalInterface extends EventDispatcher
	{
		private var _info:NativeProcessStartupInfo;
		private var _process:NativeProcess;
		private var _autoDestroy:Boolean;
		public function AIRExternalInterface(destroy:Boolean=true)
		{
			_autoDestroy=destroy;
			
			_info=new NativeProcessStartupInfo();
			
			_process=new NativeProcess();
			_process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, _callProgress);
			_process.addEventListener(IOErrorEvent.STANDARD_OUTPUT_IO_ERROR,_callError);
			_process.addEventListener(NativeProcessExitEvent.EXIT,_callComplete);
		}
		public function batch(arg:Array):void{
			call(arg[0],arg[1]);
		}
		/**
		 * 调用外部接口 
		 * @param key				外部可执行文件exe路径
		 * @param value			数据
		 */		
		public function call(key:String,value:Object):void{
			if(!value is Vector.<String>){
				throw new Error("AIRExternalInterface.call 参数必须是Vector.<String>");
				return;
			}
			_info.executable=new File(key);
			_info.arguments=value as Vector.<String>;
			try
			{
				_process.start(_info);
			} 
			catch(error:Error) 
			{
				this.dispatchEvent(new TraceableEvent(TraceableEvent.ERROR,"AIRExternalInterface","请检查APP.xml中的，supportedProfiles节点extendedDesktop 必须在前面！"));
			}
		}
		//错误处理
		private function _callError(e:ProgressEvent):void{
			this.dispatchEvent(new TraceableEvent(TraceableEvent.ERROR,"AIRExternalInterface",e.type));
			if(_autoDestroy){
				destroy();
			}
		}
		private function _callComplete(e:NativeProcessExitEvent):void{
			this.dispatchEvent(new TraceableEvent(TraceableEvent.COMPLETE,"AIRExternalInterface","Call"));
			if(_autoDestroy){
				destroy();
			}
		}
		private function _callProgress(e:ProgressEvent):void{
			this.dispatchEvent(new TraceableEvent(TraceableEvent.PROGRESS,"AIRExternalInterface","Call",0.1,1));
		}
		/**
		 * 是否正在运行中 
		 * @return 
		 * 
		 */
		public function get runing():Boolean{
			return this._process.running;
		}
		/**
		 * 彻底销毁该对象
		 */		
		public function destroy():void{
			_process.removeEventListener(ProgressEvent.STANDARD_ERROR_DATA,_callError);
			_process.removeEventListener(ProgressEvent.STANDARD_OUTPUT_DATA,_callProgress);
			_process.removeEventListener(NativeProcessExitEvent.EXIT,_callComplete);
			if(_process.running){
				_process.closeInput();
			}
			_process=null;
			_info=null;
		}
	}
}